package com.ahaoyou.core;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author LH
 * @create 2022/8/17 19:32
 * 配置顶级接口
 */
public interface ConfigChangeListener {

    Logger LOGGER = LoggerFactory.getLogger(ConfigChangeListener.class);

    ExecutorService EXECUTOR_SERVICE = new ThreadPoolExecutor(1, 1,
            Integer.MAX_VALUE, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new NamedThreadFactory("ConfigListener", 1));


    /**
     * 事件具体处理
     *
     * @param event event
     */
    void onChangeEvent(ConfigChangeEvent event);

    /**
     * 处理变更事件
     *
     * @param event 事件
     */
    default void onProcessEvent(ConfigChangeEvent event) {
        LOGGER.info("通用监听器配置处理器", event.toString());
        getExecutorService().submit(() -> {
            beforeEvent();
            try {
                onChangeEvent(event);
            } catch (Exception e) {
                e.printStackTrace();
            }
            afterEvent();
        });
    }

    default void onShutDown() {
        getExecutorService().shutdown();
    }

    default ExecutorService getExecutorService() {
        return EXECUTOR_SERVICE;
    }

    default void beforeEvent() {

    }

    default void afterEvent() {

    }
}
